package com.edu.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.edu.bean.Carimg;
import com.edu.service.CarimgService;
import com.edu.service.impl.CarimgServiceImpl;
@WebServlet("/addcarimgs.do")
@MultipartConfig(
	    maxFileSize = 1024 * 1024 * 10,    // 10MB
	    maxRequestSize = 1024 * 1024 * 50  // 50MB
	)
public class AddCarimgServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        Map<String, String> responseData = new HashMap<>(); 
        String savePath="";
		try {
			// 获取表单数据
		    int carId = Integer.parseInt(req.getParameter("carid"));

		    // 获取原有数据
		    CarimgService carimgService = new CarimgServiceImpl();
	        Carimg newCarImg = new Carimg();
		    newCarImg.setCarid(carId);

		    // 处理上传文件
		    Collection<Part> parts = req.getParts();
		    for (Part part : parts) {
		        String fieldName = part.getName();
		        String fileName = part.getSubmittedFileName();
		        
		        System.out.println("Processing field: " + fieldName);
		        
		        // 跳过非文件字段
		        if (fileName == null || fileName.isEmpty()) {
		            System.out.println("Skipping non-file field: " + fieldName);
		            continue;
		        }

		        // 校验文件
		        if (part.getSize() > 1024 * 1024) {
		            responseData.put("success", "false");
		            responseData.put("message", fieldName + "图片大小不能超过1MB");
		            return;
		        }
		        if (!part.getContentType().startsWith("image/")) {
		            responseData.put("success", "false");
		            responseData.put("message", fieldName + "只能上传图片文件");
		            return;
		        }

		        // 生成新文件名
		        String newFileName = carId + "_" + System.currentTimeMillis() + "_" + fileName;
		        savePath = "C:/PhaetonCommunityImg/favoriteCar/" + newFileName;
		        String visitPath = "/PhaetonCommunity/favoriteCar/" + newFileName;

		        // 保存文件
		        part.write(savePath);
		        System.out.println("File saved: " + savePath);
                    // 根据字段名设置对应的图片路径
                    switch (fieldName) {
                        case "carImgKV":
                            newCarImg.setCarimgkv(visitPath);
                            break;
                        case "carImgIVI":
                            newCarImg.setCarimgivi(visitPath);
                            break;
                        case "frontFender":
                            newCarImg.setFrontFender(visitPath);
                            break;
                        case "carImgAc":
                            newCarImg.setCarImgAc(visitPath);
                            break;
                        case "carImgMph":
                            newCarImg.setCarImgMph(visitPath);
                            break;
                        case "carImgAudio":
                            newCarImg.setCarImgAudio(visitPath);
                            break;
                        case "carImgSeat":
                            newCarImg.setCarImgSeat(visitPath);
                            break;
                        case "carImgSunroof":
                            newCarImg.setCarImgSunroof(visitPath);
                            break;
                        
                    }
                }

            // 更新数据库
            int result = carimgService.addCarimg(newCarImg);
            if(result == -1){
        		//添加失败时，应该把上面保存在服务器里的图片删掉
        		File file = new File(savePath);
        		if(file.exists()) {
        			file.delete();
        		}
        	} 
        } catch (Exception e) {
            responseData.put("success", "false");
            responseData.put("message", "服务器错误: " + e.getMessage());
        }

    }
        

}
